﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace SBlogCore.Common.Helpers
{
    [SkipScan]
    public class ExpressionHelper : ExpressionVisitor
    {
        private Queue<string> NameList = new Queue<string>();
        private Queue<object> ValueList = new Queue<object>();
        protected override Expression VisitConstant(ConstantExpression node)
        {
            var dd = node.Value;
            ValueList.Enqueue(dd);
            return base.VisitConstant(node);
        }
        protected override MemberBinding VisitMemberBinding(MemberBinding node)
        {
            var name = node.Member.Name;
            NameList.Enqueue(name);
            return base.VisitMemberBinding(node);
        }
        public Dictionary<string, object> GetProperty()
        {
            Dictionary<string, object> pairs = new Dictionary<string, object>();
            foreach (var item in NameList)
            {
                pairs.Add(item, ValueList.Dequeue());
            }
            return pairs;
        }
    }
    public class ExpressionCreateHelper
    {
        public Expression<Func<T, T>> CreateMember<T>(string key,object value, Type type=null)
        {
            if (type==null)
            {
                type = value.GetType();
            }
            var parameterExpression = Expression.Parameter(typeof(T), "w");
            ConstantExpression constant = Expression.Constant(value, type);
            var property = typeof(T).GetProperty(key);
            MemberAssignment bindings = Expression.Bind(property, constant);
            NewExpression newExpression = Expression.New(typeof(T));
            MemberInitExpression body = Expression.MemberInit(newExpression, bindings);
            return Expression.Lambda<Func<T, T>>(body, new ParameterExpression[1] { parameterExpression });
        }
    }
}
